/*
* Copyright (C) 2019 ~ 2021 Uniontech Software Technology Co.,Ltd.
*
* Author:     yanghongwei <yanghongwei@uniontech.com>
*
* Maintainer: yanghongwei <yanghongwei@uniontech.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "LoadingButton.h"

#include <QProgressBar>
#include <QHBoxLayout>

LoadingButton::LoadingButton(QWidget *parent)
    : QPushButton(parent)
    , m_loadingProgressBar(new QProgressBar(this))
{
    QHBoxLayout *layout = new QHBoxLayout;
    layout->setMargin(0);
    layout->addWidget(m_loadingProgressBar);
    m_loadingProgressBar->setMinimumSize(0, 0);
    m_loadingProgressBar->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred));
    m_loadingProgressBar->setRange(0, 0);
    m_loadingProgressBar->setStyleSheet("\
                        QProgressBar{\
                            border: none;\
                            border-radius:21px;\
                            color: white;\
                            background: rgba(255, 255, 255,100);\
                        }\
                        QProgressBar::chunk {\
                            border: none;\
                            border-radius:21px;\
                            background: qlineargradient(spread:reflect, x1:0, y1:0, x2:1, y2:0, stop:0 \
                                        rgba(255, 255, 255, 0), stop:0.288991 rgba(255, 255, 255, 182), \
                                        stop:0.495413 rgba(255, 255, 255, 255), stop:0.743119 rgba(255, 255, 255, 182), \
                                        stop:1 rgba(255, 255, 255, 0));\
                        }");

    this->setLayout(layout);
    stopLoading();
}

void LoadingButton::setEnableLoading(bool enable)
{
    QObject::disconnect(this, &QPushButton::clicked, this, &LoadingButton::enableLoading);
    if (enable) {
        QObject::connect(this, &QPushButton::clicked, this, &LoadingButton::enableLoading);
    }
}

void LoadingButton::stopLoading()
{
    setLoadingStatus(false);
}

void LoadingButton::enableLoading()
{
    this->setLoadingStatus(true);
}

void LoadingButton::setLoadingStatus(bool start)
{
    m_loadingProgressBar->setVisible(start);
    this->setEnabled(!start);
}
